package cn.itcast.sy7.filter;

import cn.itcast.sy7.entity.User;
import jakarta.servlet.*;
import jakarta.servlet.annotation.*;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter("/*")
public class AutoLoginFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession(false);

        if (session == null || session.getAttribute("user") == null) {
            Cookie[] cookies = httpRequest.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if ("autologin".equals(cookie.getName())) {
                        String[] parts = cookie.getValue().split("-");
                        String username = parts[0];
                        String password = parts[1];

                        if ("itcast".equals(username) && "123456".equals(password)) {
                            session = httpRequest.getSession();
                            User user = new User();
                            user.setUsername(username);
                            user.setPassword(password);
                            session.setAttribute("user", user);
                            break;
                        }
                    }
                }
            }
        }
    }
}